using MediatR;
using RBAC_Class.Domain;
using RBAC_Class.ErrorCode;
using RBAC_Class.Infrastructrue.Interfaces;
using RBAC_Class.Read.API.Application.Command.Users;
using RBAC_Class.Read.API.Dto;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System;
using NLog;

namespace RBAC_Class.Read.API.Application.CommandHandler.Users
{
    public class UserQueryCommandHandler : IRequestHandler<UserQueryCommand, APIResult<APIPaging<List<UserRoleDto>>>>
    {
        private readonly IBaseRepository<User> userRep;
        private readonly IBaseRepository<UserRole> userRoleRep;
        private readonly IBaseRepository<Role> roleRep;
        private readonly ILogger<UserQueryCommandHandler> logger;

        public UserQueryCommandHandler(IBaseRepository<User> userRep, IBaseRepository<UserRole> userRoleRep, IBaseRepository<Role> roleRep, ILogger<UserQueryCommandHandler> logger)
        {
            this.userRep = userRep;
            this.userRoleRep = userRoleRep;
            this.roleRep = roleRep;
            this.logger = logger;
        }
        /// <summary>
        /// 查询用户
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<APIPaging<List<UserRoleDto>>>> Handle(UserQueryCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var userList = userRep.GetAll().Where(x => x.IsDelete == false);
                if (!string.IsNullOrEmpty(request.UserName))
                {
                    userList = userList.Where(x => x.UserName.Contains(request.UserName));
                }
                var totalCount = userList.Count();
                var totalPage = (int)System.Math.Ceiling(totalCount * 1.0 / request.PageSize);
                var pageList = userList.OrderBy(x => x.UserID).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();

                var userDtos = new List<UserRoleDto>();
                foreach (var u in pageList)
                {
                    var userRoles = userRoleRep.GetAll().Where(x => x.UserID == u.UserID && x.IsDelete == false).ToList();
                    var roleIds = userRoles.Select(x => x.RoleID).ToList();
                    var roles = roleRep.GetAll().Where(x => roleIds.Contains(x.RoleID) && x.IsDelete == false).ToList();
                    var roleNames = roles.Select(r => r.RoleName).ToList();
                    userDtos.Add(new UserRoleDto
                    {
                        UserID = u.UserID,
                        UserName = u.UserName,
                        Password = u.Password,
                        RoleID = roleIds.FirstOrDefault(), // 兼容老字段
                        RoleName = roleNames.FirstOrDefault(), // 兼容老字段
                        RoleIDs = roleIds,
                        RoleNames = roleNames,
                        Status = u.Status,
                        CreateTime = u.CreateTime
                    });
                }
                return Task.FromResult(new APIResult<APIPaging<List<UserRoleDto>>>
                {
                    Code = ResultCode.Success,
                    Message = "查询成功",
                    Data = new APIPaging<List<UserRoleDto>>
                    {
                        TotalCount = totalCount,
                        TotalPage = totalPage,
                        Data = userDtos
                    }
                });
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "查询用户失败 - 参数: UserName={UserName}, PageIndex={PageIndex}, PageSize={PageSize}", 
                    request.UserName, request.PageIndex, request.PageSize);
                throw;
            }
        }
    }
} 